{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"https://raw.githubusercontent.com/autonomousvision/navsim/main/assets/navsim_transparent.png\" alt=\"drawing\" width=\"800\"/>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# NAVSIM Visualization Tutorial\n",
    "\n",
    "This notebook will introduce some basic plots to visualize the driving scenes in NAVSIM. All plots are created with `matplotlib` and are easy to customize for your application.\n",
    "\n",
    "## Table of Contents\n",
    "1. [Config](#config)\n",
    "2. [Birds-Eye-View](#bev)\n",
    "3. [Cameras](#camera)\n",
    "4. [Creating custom plots](#custom)\n",
    "5. [Creating GIFs](#gifs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Config <a name=\"config\"></a>\n",
    "\n",
    "NAVSIM offers two types of plots: \n",
    "- Birds-Eye-View (BEV) plots or \n",
    "- Camera plots. \n",
    "\n",
    "The LiDAR sensor can be visualized either in BEV or in camera images. All plots have a global configuration in [`navsim/visualization/config.py`](https://github.com/autonomousvision/navsim/blob/main/navsim/navsim/visualization/config.py). In this Python file, you can configure all colors or dimensions. The LiDAR point cloud can be colored in any colormap, showing the distance to the ego vehicle or the height of each point. In this tutorial, we first instantiate a `SceneFilter` and `SceneLoader` from the mini split."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from pathlib import Path\n",
    "\n",
    "import hydra\n",
    "from hydra.utils import instantiate\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from navsim.common.dataloader import SceneLoader\n",
    "from navsim.common.dataclasses import SceneFilter, SensorConfig\n",
    "\n",
    "SPLIT = \"mini\"  # [\"mini\", \"test\", \"trainval\"]\n",
    "FILTER = \"all_scenes\"\n",
    "\n",
    "hydra.initialize(config_path=\"../navsim/planning/script/config/common/scene_filter\")\n",
    "cfg = hydra.compose(config_name=FILTER)\n",
    "scene_filter: SceneFilter = instantiate(cfg)\n",
    "openscene_data_root = Path(os.getenv(\"OPENSCENE_DATA_ROOT\"))\n",
    "\n",
    "scene_loader = SceneLoader(\n",
    "    openscene_data_root / f\"navsim_logs/{SPLIT}\",\n",
    "    openscene_data_root / f\"sensor_blobs/{SPLIT}\",\n",
    "    scene_filter,\n",
    "    sensor_config=SensorConfig.build_all_sensors(),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Birds-Eye-View <a name=\"bev\"></a>\n",
    "\n",
    "The Birds-Eye-View (BEV) visualization in NAVSIM is useful for overviewing the map, bounding-box annotations, or the LiDAR point cloud. In standard setting, the BEV plot includes a 64m $\\times$ 64m frame centered at the rear axle of the ego vehicle (excluding LiDAR for simplicity). First, we take a random token and load a scene to visualize."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "token = np.random.choice(scene_loader.tokens)\n",
    "scene = scene_loader.get_scene_from_token(token)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The function `plot_bev_frame` takes a `Scene` and index of the step to visualize (history or future). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from navsim.visualization.plots import plot_bev_frame\n",
    "\n",
    "frame_idx = scene.scene_metadata.num_history_frames - 1 # current frame\n",
    "fig, ax = plot_bev_frame(scene, frame_idx)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The function `plot_bev_with_agent` visualizes the trajectory of an <span style=\"color:#DE7061\">agent</span> in comparison to the <span style=\"color:#59a14f\">human vehicle operator</span> at the current frame. This notebook shows an example of the naive `ConstantVelocityAgent`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from navsim.visualization.plots import plot_bev_with_agent\n",
    "from navsim.agents.constant_velocity_agent import ConstantVelocityAgent\n",
    "\n",
    "agent = ConstantVelocityAgent()\n",
    "fig, ax = plot_bev_with_agent(scene, agent)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cameras <a name=\"bev\"></a>\n",
    "\n",
    "The agents in NAVSIM have access to eight cameras surrounding the vehicle. The function `plot_cameras_frame` shows the cameras in a 3 $\\times$ 3 grid with cameras in each direction of the ego-vehicle and the BEV plot in the center. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from navsim.visualization.plots import plot_cameras_frame\n",
    "\n",
    "fig, ax = plot_cameras_frame(scene, frame_idx)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With `plot_cameras_frame_with_annotations`, you can visualize the bounding-box annotations in the camera images."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from navsim.visualization.plots import plot_cameras_frame_with_annotations\n",
    "\n",
    "fig, ax = plot_cameras_frame_with_annotations(scene, frame_idx)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With `plot_cameras_frame_with_lidar`, you can visualize the LiDAR point cloud in the camera images."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from navsim.visualization.plots import plot_cameras_frame_with_lidar\n",
    "\n",
    "fig, ax = plot_cameras_frame_with_lidar(scene, frame_idx)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Creating custom plots <a name=\"custom\"></a>\n",
    "\n",
    "The plots in NAVSIM use `matplotlib` and either add elements to a `plt.Axes` object or return the full `plt.Figure`. Functions in [`navsim/visualization/`](https://github.com/autonomousvision/navsim/blob/main/navsim/navsim/visualization) can be re-used to create custom plots. In this example, we create a plot for the bounding-box annotations and the LiDAR point cloud."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from navsim.visualization.plots import configure_bev_ax\n",
    "from navsim.visualization.bev import add_annotations_to_bev_ax, add_lidar_to_bev_ax\n",
    "\n",
    "\n",
    "fig, ax = plt.subplots(1, 1, figsize=(6, 6))\n",
    "\n",
    "ax.set_title(\"Custom plot\")\n",
    "\n",
    "add_annotations_to_bev_ax(ax, scene.frames[frame_idx].annotations)\n",
    "add_lidar_to_bev_ax(ax, scene.frames[frame_idx].lidar)\n",
    "\n",
    "# configures frame to BEV view\n",
    "configure_bev_ax(ax)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Creating GIFs <a name=\"gifs\"></a>\n",
    "\n",
    "You can transform frame-wise plots into short animated GIFs. Give any function to `frame_plot_to_gif`, which takes a `Scene` and `frame_idx` as input (ie. `plot_cameras_frame_with_annotations`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from navsim.visualization.plots import frame_plot_to_gif\n",
    "\n",
    "frame_indices = [idx for idx in range(len(scene.frames))]  # all frames in scene\n",
    "file_name = f\"./{token}.gif\"\n",
    "images = frame_plot_to_gif(file_name, plot_cameras_frame_with_annotations, scene, frame_indices)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "navsim",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
